//
//  SNHomePageViewController.m
//  project
//
//  Created by 黄建华 on 2017/11/20.
//  Copyright © 2017年 黄建华. All rights reserved.
//
#import "SNHomePageViewController.h"
#import "CalendarViewController.h"
#import "CalendarButton.h"
#import "SNHomePageTableViewCell.h"
#import "SNStepChartVc.h"
#import "SNSleepDetailVc.h"
#import "SNHearDetailVc.h"
#import "SNBpDetailVc.h"
#import "SNOxDetailVc.h"
#import "FSCalendar.h"
#import "SNHealthyCheckVc.h"
#import "SNHomeHeadView.h"
#import "project-Swift.h"
@interface SNHomePageViewController () <UITableViewDelegate, UITableViewDataSource, FSCalendarDelegate, FSCalendarDataSource, FSCalendarDelegateAppearance, UIScrollViewDelegate, UIGestureRecognizerDelegate>{
    //日历控件
    FSCalendar *_calendar;
    //
    UIView *_calendarView;
}

@property (nonatomic, strong) ZZCACircleProgress            *stepCircle; // 步数圆圈
@property (nonatomic, strong) SNStepChartView               *stepChartView; // 详情
@property (nonatomic, strong) UIButton                      *stepDetailButton;
@property (nonatomic, strong) UILabel                       *currentDateLabel; // 当前日期
@property (nonatomic, strong) UIView                        *calendarView;
@property (nonatomic, strong) CalendarButton                *calendarBtn; // 日历按钮
@property (nonatomic, strong) CalendarViewController        *CalendarView;
@property (nonatomic, strong) UIButton                      *detailChartButton;
@property (nonatomic, strong) SNCustomLabel                 *distanceLabel;
@property (nonatomic, strong) SNCustomLabel                 *StepLabel;
@property (nonatomic, strong) SNCustomLabel                 *calorLabel;
@property (nonatomic, strong) SNHomePageShowStepDetailLabel *distanceUnitLabel;
@property (nonatomic, strong) SNHomePageShowStepDetailLabel *stepUnitLabel;
@property (nonatomic, strong) SNHomePageShowStepDetailLabel *calorUnitLabel;

@property (nonatomic, strong) UIScrollView   *headView;               //下拉视图
@property (nonatomic, strong) UITableView    *tableView;
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, strong) NSMutableArray *pushArray;
@property (nonatomic, strong) SNHomeHeadView *leftView;
@property (nonatomic, strong) SNHomeHeadView *centerView;
@property (nonatomic, strong) SNHomeHeadView *rightView;
@property (nonatomic, strong) UIImageView    *animateView;
@property (nonatomic, strong) UIView         *bgView;
@property (nonatomic, assign) BOOL           isUpdateView;
@end

@implementation SNHomePageViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [KK_WeatherModel startUpdateLocation];
    [self addNavView];
    [self initTabelView];
    [SN_Net uploadUserLog];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(BecomeActive) name:UIApplicationDidBecomeActiveNotification object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(Becomeback) name:UIApplicationDidEnterBackgroundNotification object:nil];
    
    SNShadowView *shadowLine = [[SNShadowView alloc] init];
    shadowLine.frame = SNFRAME(0, 20+FitSimpleIpx(0, 20) + 44, HHHWIDTH, 0);
    [shadowLine showWithType:1];
    [self.view addSubview:shadowLine];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self performSelector:@selector(BecomeActive) withObject:nil afterDelay:0.2f];
    
    NSInteger width = 0;
    if (KK_ShareData.lastVcTag > KK_ShareData.currentVCTag) {
        width = HHHWIDTH;
    }
    if (KK_ShareData.lastVcTag < KK_ShareData.currentVCTag) {
        width = -HHHWIDTH;
    }
    
    if (KK_ShareData.lastVcTag == KK_ShareData.currentVCTag) {
        width = 0;
    }
    if (width != 0) {
        if (_bgView) {
            [_bgView removeFromSuperview];
            _bgView = nil;
        }
        if (_animateView) {
            [_animateView removeFromSuperview];
            _animateView = nil;
        }
        
        _animateView = [[UIImageView alloc]initWithFrame:self.view.frame];
        [self.view addSubview:_animateView];
        UIGraphicsBeginImageContextWithOptions(CGSizeMake(HHHWIDTH, HHHHEIGHT), NO, 0.0);
        [self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
        UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        _animateView.image = viewImage;
        
        _bgView                 = [[UIView alloc] initWithFrame:self.view.frame];
        _bgView.backgroundColor = self.view.backgroundColor;
        [self.view addSubview:_bgView];
        [self.view bringSubviewToFront:_animateView];
        _animateView.frame  = SNFRAME(width, 0, HHHWIDTH, HHHHEIGHT);
        _animateView.hidden = NO;
        _bgView.hidden      = NO;
        [UIView animateWithDuration:VIEWANIMATETIME animations:^{
            _animateView.frame = SNFRAME(0, 0, HHHWIDTH, HHHHEIGHT);
        } completion:^(BOOL finished) {
            _animateView.hidden = YES;
            _bgView.hidden = YES;
        }];
    }
//    [self makeSleep];
}

- (void)makeSleep {
    SN_PublicClass.todaySleepArray = [NSMutableArray array];
    SleepSubModel *model11 = [[SleepSubModel alloc] init];
    model11.subdeep  = 0;
    model11.sublight = 0;
    model11.subsober = 0;
    NSMutableArray *detail11 = [NSMutableArray array];
    [detail11 addObject:@"16423"];
    [detail11 addObject:@"32769"];
    [detail11 addObject:@"1"];
    [detail11 addObject:@"16398"];
    [detail11 addObject:@"21"];
    [detail11 addObject:@"16405"];
    [detail11 addObject:@"7"];
    [detail11 addObject:@"16406"];
    [detail11 addObject:@"1"];
    [detail11 addObject:@"16435"];
    [detail11 addObject:@"35"];
    [detail11 addObject:@"0"];
    [detail11 addObject:@"0"];
    [detail11 addObject:@"0"];
    [detail11 addObject:@"0"];
    [detail11 addObject:@"0"];
    [detail11 addObject:@"0"];
    [detail11 addObject:@"0"];
    [detail11 addObject:@"0"];
    [detail11 addObject:@"0"];
    [detail11 addObject:@"0"];
    [detail11 addObject:@"0"];
    [detail11 addObject:@"0"];
    [detail11 addObject:@"0"];
    
    for (int i = 0; i < detail11.count; i++) {
        NSInteger number1      = [[detail11 objectAtIndex:i]integerValue];
        NSInteger sleepStatus1 = (UInt8)(number1 >> 14);
        NSInteger sleepTime1   = (UInt16)number1 & 0x3FFF;
        if (sleepStatus1 == 0) {
            model11.sublight += sleepTime1;
        } else if (sleepStatus1 == 1) {
            model11.subdeep += sleepTime1;
        } else if (sleepStatus1 == 2) {
            model11.subsober += sleepTime1;
        }
    }
    NSString *startTime1 = @"2018-04-25 00:00:00";
    NSString *endTime1   = @"2018-04-25 03:42:00";
    model11.substartTime = startTime1;
    model11.subendTime   = endTime1;
    model11.subdate      = [endTime1 componentsSeparatedByString:@" "][0];
    model11.subsleepData = [NSMutableArray arrayWithArray:detail11];
    [SN_PublicClass.todaySleepArray addObject:model11];
    
    SleepSubModel *model1 = [[SleepSubModel alloc] init];
    model1.subdeep  = 0;
    model1.sublight = 0;
    model1.subsober = 0;
    NSMutableArray *detail1 = [NSMutableArray array];
    [detail1 addObject:@"16405"];
    [detail1 addObject: @"21"];
    [detail1 addObject: @"16404"];
    
    [detail1 addObject: @"23"];
    [detail1 addObject: @"16399"];
    [detail1 addObject: @"22"];
    [detail1 addObject: @"16414"];
    [detail1 addObject: @"19"];
    [detail1 addObject: @"0"];
    [detail1 addObject: @"0"];
    [detail1 addObject: @"0"];
    [detail1 addObject: @"0"];
    [detail1 addObject: @"0"];
    [detail1 addObject: @"0"];
    [detail1 addObject: @"0"];
    [detail1 addObject: @"0"];
    [detail1 addObject: @"0"];
    [detail1 addObject: @"0"];
    [detail1 addObject: @"0"];
    [detail1 addObject: @"0"];
    [detail1 addObject: @"0"];
    [detail1 addObject: @"0"];
    [detail1 addObject: @"0"];
    [detail1 addObject: @"0"];
    
    for (int i = 0; i < detail1.count; i++) {
        NSInteger number      = [[detail1 objectAtIndex:i]integerValue];
        NSInteger sleepStatus = (UInt8)(number >> 14);
        NSInteger sleepTime   = (UInt16)number & 0x3FFF;
        if (sleepStatus == 0) {
            model1.sublight += sleepTime;
        } else if (sleepStatus == 1) {
            model1.subdeep += sleepTime;
        } else if (sleepStatus == 2) {
            model1.subsober += sleepTime;
        }
    }
    NSString *startTime = @"2018-04-25 04:09:00";
    NSString *endTime   = @"2018-04-25 07:04:00";
    model1.substartTime = startTime;
    model1.subendTime   = endTime;
    model1.subdate      = [endTime componentsSeparatedByString:@" "][0];
    model1.subsleepData = [NSMutableArray arrayWithArray:detail1];
    [SN_PublicClass.todaySleepArray addObject:model1];
    [SleepModel sleepTransEnd];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [[self class] cancelPreviousPerformRequestsWithTarget:self selector:@selector(BecomeActive) object:nil];
}

- (void)addNavView {
    UIView *naView = [[UIView alloc] init];
    
    naView.frame           = CGRectMake(0, 20+FitSimpleIpx(0, 20), kSCREEN_WIDTH, 44);
    naView.backgroundColor = UIColorRGB(76, 192, 234);
    [self.view addSubview:naView];
    
    _calendarBtn                 = [[CalendarButton alloc] initWithFrame:SNFRAME(0, 0, 44, 44)];
    _calendarBtn.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 2, 0);
    [_calendarBtn addTarget:self action:@selector(crectCalendar) forControlEvents:UIControlEventTouchUpInside];
    [naView addSubview:_calendarBtn];
    
    _currentDateLabel               = [[UILabel alloc] initWithFrame:SNFRAME(0, (44-25)/2.0, HHHWIDTH, 25)];
    _currentDateLabel.textColor     = SNCOLORBLACK;
    _currentDateLabel.textAlignment = NSTextAlignmentCenter;
    _currentDateLabel.font          = SNFONT(20.0);
    [naView addSubview:_currentDateLabel];
    _calendarBtn.center = CGPointMake(26, _currentDateLabel.center.y);
    
    UIButton *backButton = [[UIButton alloc] init];
    backButton.frame  = SNFRAME(0, 0, 100, 33);
    backButton.center = _currentDateLabel.center;
    [backButton addTarget:self
                   action:@selector(backButtonClick)
         forControlEvents:UIControlEventTouchUpInside];
    [naView addSubview:backButton];
    
    UIButton *shareBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    shareBtn.frame = CGRectMake(screenWidth - 44 - 44 - 10, 0, 44, 44);
    [shareBtn setImageNormal:@"分享share"];
    [shareBtn addTarget:self
                 action:@selector(shareButtonClick)
       forControlEvents:UIControlEventTouchUpInside];
    //    [naView addSubview:shareBtn];
    shareBtn.center = CGPointMake(screenWidth - 44 - 44 - 10 + 22, _currentDateLabel.center.y);
    
    _detailChartButton       = [UIButton buttonWithType:UIButtonTypeCustom];
    _detailChartButton.frame = CGRectMake(screenWidth - 44 - 5, 0, 44, 44);
    [_detailChartButton setImageNormal:@"数据"];
    _detailChartButton.imageEdgeInsets = UIEdgeInsetsMake(2, 2, 4, 2);
    [_detailChartButton addTarget:self
                           action:@selector(detailChartButtonClick)
                 forControlEvents:UIControlEventTouchUpInside];
    [naView addSubview:_detailChartButton];
    _detailChartButton.center = CGPointMake(screenWidth - 44 - 5 + 22, _currentDateLabel.center.y);
}

#pragma mark --- 应用切换到前台模式 ---

- (void)initstepCircle {
    _leftView   = [[SNHomeHeadView alloc]initWithFrame:CGRectMake(0, 10, HHHWIDTH, _headView.height)];
    _centerView = [[SNHomeHeadView alloc]initWithFrame:CGRectMake(HHHWIDTH, 10, HHHWIDTH, _headView.height)];
    DEF_WEAKSELF_(SNHomePageViewController)
    _centerView.hiddenBlock = ^(BOOL hidden) {
        weakSelf.leftView.hidden  = hidden;
        weakSelf.rightView.hidden = hidden;
    };
    _rightView = [[SNHomeHeadView alloc]initWithFrame:CGRectMake(HHHWIDTH*2, 10, HHHWIDTH, _headView.height)];
    [_headView addSubview:_leftView];
    [_headView addSubview:_centerView];
    [_headView addSubview:_rightView];
    [self BecomeActive];
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    if (![scrollView isKindOfClass:[UITableView class]]) {
        [self reloadScrollView];
        //移动到中间
        _headView.contentOffset = CGPointMake(HHHWIDTH, 0);
    }
}

- (void)reloadScrollView {
    CGPoint offset = [_headView contentOffset];
    
    if (offset.x > HHHWIDTH) { //向左滑动
        NSDate *nextDate = [SN_PublicClass.selectDate dateAfterDay:+1];
        [self goToDay:nextDate];
    } else if (offset.x < HHHWIDTH) { //向右滑动
        NSDate *beforeDate = [SN_PublicClass.selectDate dateAfterDay:-1];
        [self goToDay:beforeDate];
    }
}

- (void)goToDay:(NSDate *)date {
    NSInteger nowCount = [NSDate compareDate:[NSDate date] withAnotherDay:date];
    
    if (nowCount == 1) {
        SHOWMBProgressHUD(SN_Text(@"不能选择未来时间！"), nil, nil, NO, 1.0);
        return;
    }
    SN_PublicClass.selectDate = date;
    [self updateAlldata];
    [self updateTableView];
}

// 更新当前所有UI显示
- (void)updateAlldata {
    //主页日期
    _calendarBtn.selectDateLabel.text = SNSTRING(@(SN_PublicClass.selectDate.day));
    _currentDateLabel.text            = [SN_PublicClass showDateWithType:0];
    
    SportModel *leftModel = [SportModel getSportModelFromDBWith:[SN_PublicClass.selectDate dateAfterDay:-1]];
    _leftView.model = leftModel;
    
    SportModel *centerModel = [SportModel getSportModelFromDBWith:SN_PublicClass.selectDate];
    _centerView.model = centerModel;
    
    SportModel *rightModel = [SportModel getSportModelFromDBWith:[SN_PublicClass.selectDate dateAfterDay:+1]];
    _rightView.model = rightModel;
}

// 入口 1:日期选择或者 2:蓝牙同步完刷新这里
- (void)updateTableView {
    _dataArray = [[NSMutableArray alloc] init];
    NSMutableArray *sleep = [NSMutableArray array];
    [sleep addObject:SNIMAGENAME(@"睡眠新")];
    
    SleepModel *sleepModel     = [SleepModel getSleepModelFromDBWith:SN_PublicClass.selectDate];
    NSString   *showSleepTotal = [NSString stringWithFormat:@"%d%@ %d%@", sleepModel.durations/60, SN_Text(@"h"), sleepModel.durations%60, SN_Text(@"mins")];
    
    NSString *quality         = @"";
    NSString *lastTime        = @"";
    NSString *showSleepDetail = [NSString stringWithFormat:@"%@: %@", SN_Text(@"睡眠质量"), SN_Text(@"暂无数据")];
    if (sleepModel.durations > 0) {
        if (sleepModel.sleepsubArray) {
            SleepSubModel *model = [sleepModel.sleepsubArray firstObject];
            quality = sleepModel.compareQuality;
            NSDate *startDate = [NSDate dateByStringFormat:model.substartTime];
            NSDate *endDate   = [startDate dateByAddingTimeInterval:model.subtotalduration*60];
            lastTime        = [[endDate dateToString] componentsSeparatedByString:@" "][1];
            lastTime        = [NSString subString:lastTime withToIndex:5];
            showSleepDetail = [NSString stringWithFormat:@"%@: %@ %@", SN_Text(@"睡眠质量"), quality, lastTime];
        }
    }
    [sleep addObject:showSleepTotal];
    [sleep addObject:showSleepDetail];
    [sleep addObject:SN_Text(@"睡眠记录")];
    [sleep addObject:@"0"];
    
    NSMutableArray *check = [NSMutableArray array];
    [check addObject:SNIMAGENAME(@"体检")];
    [check addObject:@""];
    [check addObject:@""];
    [check addObject:SN_Text(@"我的体检")];
    [check addObject:@"1"];
    
    NSMutableArray *heart = [NSMutableArray array];
    [heart addObject:SNIMAGENAME(@"心率新")];
    
    HeartModel *heartModel     = [HeartModel getHeartModelFromDBWith:SN_PublicClass.selectDate];
    NSString   *showHeartValue = [NSString stringWithFormat:@"%d - %d bpm", heartModel.heartMin, heartModel.heartMax];
    
    NSString *hvalue          = [NSString string];
    NSString *hlastTime       = [NSString string];
    NSString *showHeartDetail = [NSString stringWithFormat:@"%@:%@", SN_Text(@"最后一次"), SN_Text(@"暂无数据")];
    if (heartModel.heartAllValueArray.count > 0) {
        hvalue          = [NSString stringWithFormat:@"%@", [heartModel.heartAllValueArray lastObject]];
        hlastTime       = [heartModel.heartAllTimeArray lastObject];
        hlastTime       = [NSString subString:hlastTime withToIndex:5];
        showHeartDetail = [NSString stringWithFormat:@"%@:%@ %@", SN_Text(@"最后一次"), hvalue, hlastTime];
    }
    [heart addObject:showHeartValue];
    [heart addObject:showHeartDetail];
    [heart addObject:SN_Text(@"心率记录")];
    [heart addObject:@"2"];
    
    NSMutableArray *ox = [NSMutableArray array];
    [ox addObject:SNIMAGENAME(@"血氧新")];
    
    OxModel  *oModel      = [OxModel getOxModelFromDBWith:SN_PublicClass.selectDate];
    NSString *showOxValue = @"0 %";
    showOxValue = [NSString stringWithFormat:@"%d ~ %d %%", oModel.oxMin, oModel.oxMax];
    
    NSString *ovalue       = [NSString string];
    NSString *olasttime    = [NSString string];
    NSString *showOxDetail = [NSString stringWithFormat:@"%@:%@", SN_Text(@"最后一次"), SN_Text(@"暂无数据")];
    if (oModel.oxsuArrayAuto.count > 0) {
        oxSubModel *model = [oModel.oxsuArrayAuto lastObject];
        ovalue       = [NSString stringWithFormat:@"%d %%", model.oxValue];
        olasttime    = [[model.updateTime componentsSeparatedByString:@" "]lastObject];
        olasttime    =  [NSString subString:olasttime withToIndex:5];
        showOxDetail = [NSString stringWithFormat:@"%@:%@ %@", SN_Text(@"最后一次"), ovalue, olasttime];
    }
    [ox addObject:showOxValue];
    [ox addObject:showOxDetail];
    [ox addObject:SN_Text(@"血氧记录")];
    [ox addObject:@"3"];
    
    NSMutableArray *bp = [NSMutableArray array];
    [bp addObject:SNIMAGENAME(@"血压新")];
    BpModel *bpModel = [BpModel getBpModelFromDBWith:SN_PublicClass.selectDate];
    
    NSString *showBPValue = [NSString stringWithFormat:@"%d - %d mmHg", bpModel.SBPAve, bpModel.DBPAve];
    
    NSString *bs           = [NSString string];
    NSString *blasttime    = [NSString string];
    NSString *showBpDetail = [NSString stringWithFormat:@"%@:%@", SN_Text(@"最后一次"), SN_Text(@"暂无数据")];
    if (bpModel.bpSuArray.count > 0) {
        bpSubModel *model = [bpModel.bpSuArray lastObject];
        bs           = [NSString stringWithFormat:@"%d - %d", model.SBPValue, model.DBPValue];
        blasttime    = [[model.updateTime componentsSeparatedByString:@" "]lastObject];
        blasttime    =  [NSString subString:blasttime withToIndex:5];
        showBpDetail = [NSString stringWithFormat:@"%@:%@ %@", SN_Text(@"最后一次"), bs, blasttime];
    }
    
    [bp addObject:showBPValue];
    [bp addObject:showBpDetail];
    [bp addObject:SN_Text(@"血压记录")];
    [bp addObject:@"4"];
    
    [_dataArray addObject:sleep];
    
    // 睡眠 体检 心率 血氧 血压(默认第一个都是睡眠页)
    _pushArray = [NSMutableArray array];
    [_pushArray addObject:@"0"];
    if (KK_BLEConnect.isBoindDevice) {
        // 通用
        if (SN_USER.heart || SN_USER.oxygen || SN_USER.bistoryPressure) {
            [_dataArray addObject:check];
            [_pushArray addObject:@"1"];
        }
        if (SN_USER.heart) {
            [_dataArray addObject:heart];
            [_pushArray addObject:@"2"];
        }
        if (SN_USER.bistoryPressure) {
            [_dataArray addObject:bp];
            [_pushArray addObject:@"4"];
        }
        if (SN_USER.oxygen) {
            [_dataArray addObject:ox];
            [_pushArray addObject:@"3"];
        }
        //兼容
        if (_pushArray.count == 1) {
            [SN_Net getDeviceSFromServerWithSuccess:nil fail:nil];
            if ([KK_BLEModel.bleName isEqualToString:@"X10pro"] || [KK_BLEModel.bleName isEqualToString:@"X10Pro"] || [KK_BLEModel.bleName isEqualToString:@"X10plus"] || [KK_BLEModel.bleName isEqualToString:@"X10Plus"]) {
                [_dataArray addObject:check];
                [_pushArray addObject:@"1"];
                [_dataArray addObject:heart];
                [_pushArray addObject:@"2"];
                [_dataArray addObject:bp];
                [_pushArray addObject:@"4"];
                [_dataArray addObject:ox];
                [_pushArray addObject:@"3"];
            }
        }
    } else {
        [_dataArray addObject:check];
        [_pushArray addObject:@"1"];
        [_dataArray addObject:heart];
        [_pushArray addObject:@"2"];
        [_dataArray addObject:bp];
        [_pushArray addObject:@"4"];
        [_dataArray addObject:ox];
        [_pushArray addObject:@"3"];
    }
    SN_PublicClass.function = [NSMutableArray arrayWithArray:_pushArray];
    [_tableView reloadData];
}

- (void)initTabelView {
    _tableView                              = [[UITableView alloc]initWithFrame:CGRectMake(0, 20+FitSimpleIpx(0, 20)+44, HHHWIDTH, HHHHEIGHT -20-FitSimpleIpx(0, 20)-44-49 +20) style:UITableViewStyleGrouped];
    _tableView.delegate                     = self;
    _tableView.dataSource                   = self;
    _tableView.backgroundColor              = [UIColor clearColor];
    _tableView.separatorStyle               = UITableViewCellSeparatorStyleNone;
    _tableView.showsVerticalScrollIndicator = NO;
    [self.view addSubview:_tableView];
    
    [self initWithHeadView];
    
    _tableView.tableHeaderView = _headView;
    UIView *blackView = [[UIView alloc] init];
    blackView.frame           = CGRectMake(0, -200, HHHWIDTH, 150);
    blackView.backgroundColor = [UIColor colorFromHex:0x4b4b4b];
    [_tableView addSubview:blackView];
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
    header.backgroundColor            = [UIColor colorFromHex:0x4b4b4b];
    header.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhite;
    // 设置文字
    [header setTitle:SN_Text(@"下拉刷新") forState:MJRefreshStateIdle];
    [header setTitle:SN_Text(@"松开刷新") forState:MJRefreshStatePulling];
    [header setTitle:SN_Text(@"加载 ...") forState:MJRefreshStateRefreshing];
    
    // 设置字体
    header.stateLabel.font           = [UIFont systemFontOfSize:15];
    header.lastUpdatedTimeLabel.font = [UIFont systemFontOfSize:14];
    if (SN_USER.lastUpdateTime.length > 0) {
        header.lastUpdatedTimeLabel.text = [NSString stringWithFormat:@"%@:%@", SN_Text(@"上次更新"), SN_USER.lastUpdateTime];
    } else {
        header.lastUpdatedTimeLabel.text = [NSString stringWithFormat:@"%@:%@", SN_Text(@"上次更新"), [[NSDate date]dateToString]];
    }
    // 设置颜色
    header.stateLabel.textColor           = SNCOLORGRAY;
    header.lastUpdatedTimeLabel.textColor = SNCOLORGRAY;
    // 设置刷新控件
    _tableView.mj_header                          = header;
    _tableView.mj_header.automaticallyChangeAlpha = YES;
}

- (void)initWithHeadView {
    CGFloat headViewHeight = 0;
    
    headViewHeight  = FitSimpleSize(237, 263, 283, 283, 283);
    headViewHeight -= 10;
    
    _headView                                = [[UIScrollView alloc]init];
    _headView.frame                          = CGRectMake(0, 0, HHHWIDTH, headViewHeight);
    _headView.pagingEnabled                  = YES;
    _headView.delegate                       = self;
    _headView.backgroundColor                = UIColorRGB(76, 192, 234);
    _headView.contentSize                    = CGSizeMake(HHHWIDTH*3, 0);
    _headView.contentOffset                  = CGPointMake(HHHWIDTH, 0);
    _headView.showsHorizontalScrollIndicator = NO;
    [self initstepCircle]; //初始化圆圈
}

- (void)cheakHealthyClick {
    if ([_currentDateLabel.text isEqualToString:SN_Text(@"今天")]) {
        SNHealthyCheckVc *vc = [[SNHealthyCheckVc alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
        CustomTabBar *tabBar = (CustomTabBar *)self.tabBarController;
        [tabBar hiddenTheTabBarView];
    } else {
        SHOWMBProgressHUD(SN_Text(@"返回今天才能体检"), nil, nil, NO, 1.0);
    }
}

- (void)loadNewData {
    NSLog(@"开始刷新");
    [KK_BLESend updateData];
    [self endRefreshing];
}

- (void)endRefreshing {
    __unsafe_unretained UITableView *tableView = self.tableView;
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 结束刷新
        [tableView.mj_header endRefreshing];
    });
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 20;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView        *view      = [UIView new];
    SNCustomLabel *infolabel = [[SNCustomLabel alloc] initWithFrame:SNFRAME(10, 5, 200, 20)];
    
    infolabel.text          = SN_Text(@"你的健康");
    infolabel.font          = SNFONTMIN(15);
    infolabel.textAlignment = NSTextAlignmentLeft;
    [view addSubview:infolabel];
    return view;
}

#pragma mark - 创建日历
- (void)crectCalendar {
    if (_calendarView) {
        [_calendarView removeAllSubviews];
        _calendarView = nil;
    }
    if (_CalendarView) {
        [_CalendarView.view removeAllSubviews];
        _CalendarView = nil;
    }
    
    if (!_calendarView) {
        _calendarView       = [[UIView alloc] init];
        _calendarView.frame = SNFRAME(0, 220, HHHWIDTH, 440);
        [self.view addSubview:_calendarView];
    }
    if (!_CalendarView) {
        _CalendarView = [[CalendarViewController alloc] init];
        [_calendarView addSubview:_CalendarView.view];
    }
    
    _calendarView.transform      = CGAffineTransformMakeScale(0.9f, 0.9f);
    _CalendarView.view.transform = CGAffineTransformMakeScale(0.9f, 0.9f);
    
    [_calendarView popupWithtype:PopupViewOption_colorLump succeedBlock:^(UIView *View)
     {
         View.center = CGPointMake(HHHWIDTH/2, HHHHEIGHT/2 +33 - FitSimpleSize(50, 50, 90, 125, 145));
     }              dismissBlock:^(UIView *View)
     
     {
     }];
    
    DEF_WEAKSELF_(SNHomePageViewController)
    _CalendarView.selectDateBlock = ^(NSDate *date) {
        //        NSLog(@"选择了日期 >>>>%@", date);
        SN_PublicClass.selectDate      = date;
        weakSelf.currentDateLabel.text = [SN_PublicClass showDateWithType:0];
        [weakSelf.calendarView dismissPopup];
        [weakSelf updateAlldata];
        [weakSelf updateTableView];
    };
    _CalendarView.cancelBlock = ^()
    {
        [weakSelf.calendarView dismissPopup];
    };
}

- (void)backButtonClick {
    NSUInteger nowCount = [NSDate compareDate:[NSDate date] withAnotherDay:SN_PublicClass.selectDate];
    
    if (nowCount == 0) {
        return;
    }
    SN_PublicClass.selectDate = [NSDate date];
    [self updateAlldata];
    [self updateTableView];
}

// 分享
- (void)shareButtonClick {
    UIGraphicsBeginImageContext(CGSizeMake(screenWidth, screenHeight));
    
    [[UIApplication sharedApplication].delegate.window.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    NSMutableArray *items = [[NSMutableArray alloc] init];
    [items addObject:image];
    
    UIActivityViewController *activityViewController = [[UIActivityViewController alloc] initWithActivityItems:items applicationActivities:nil];
    NSMutableArray           *excludedActivityTypes  = [NSMutableArray arrayWithArray:@[
                                                                                        UIActivityTypeMessage, UIActivityTypeMail, UIActivityTypePrint, UIActivityTypeCopyToPasteboard, UIActivityTypeAssignToContact, UIActivityTypeSaveToCameraRoll, UIActivityTypeAddToReadingList, UIActivityTypePostToFlickr, UIActivityTypePostToVimeo, UIActivityTypePostToTencentWeibo, UIActivityTypeAirDrop,
                                                                                        UIActivityTypeOpenInIBooks]];
    activityViewController.excludedActivityTypes = excludedActivityTypes;
    
    [self presentViewController:activityViewController animated:YES completion:nil];
    activityViewController.completionWithItemsHandler = ^(UIActivityType __nullable activityType, BOOL completed, NSArray *__nullable returnedItems, NSError *__nullable activityError){
    };
}

// 步数 周月年图表查看
- (void)detailChartButtonClick {
    SNStepChartVc *vc = [[SNStepChartVc alloc] init];
    
    [self.navigationController pushViewController:vc animated:YES];
    CustomTabBar *tabBar = (CustomTabBar *)self.tabBarController;
    [tabBar hiddenTheTabBarView];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _dataArray.count/2 + _dataArray.count %2;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    CGFloat row = 0;
    
    row = HHHWIDTH / 2.0-FitW(15)*0.5;
    
    return row;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString         *identifier = @"SNHomePageTableViewCell";
    SNHomePageTableViewCell *cell       = [tableView cellForRowAtIndexPath:indexPath];
    
    if (nil == cell) {
        cell = [[SNHomePageTableViewCell alloc] initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:identifier];
    }
    for (int i = 0; i < _dataArray.count; i += 2) {
        if (i/2 == indexPath.row) {
            if (i%2 == 0) {
                [cell updateMainCellLeft:_dataArray[i]];
                if (i+1 < _dataArray.count) {
                    [cell updateMainCellRight:_dataArray[i+1]];
                }
            }
        }
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    [cell.button addTarget:self action:@selector(homePageCellClick:) forControlEvents:UIControlEventTouchUpInside];
    [cell.button2 addTarget:self action:@selector(homePageCellClick:) forControlEvents:UIControlEventTouchUpInside];
    return cell;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (void)homePageCellClick:(UIButton *)sender {
    NSString *s = [NSString stringWithFormat:@"%ld", sender.tag];
    
    if (s.intValue == 0) {
        SNSleepDetailVc *vc = [[SNSleepDetailVc alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
    } else if (s.intValue == 1) {
        SNCheckVc *vc = [[SNCheckVc alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
    } else if (s.intValue == 2) {
        SNHearDetailVc *vc = [[SNHearDetailVc alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
    } else if (s.intValue == 3) {
        SNOxDetailVc *vc = [[SNOxDetailVc alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
    } else if (s.intValue == 4) {
        SNBpDetailVc *vc = [[SNBpDetailVc alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
    }
    
    CustomTabBar *tabBar = (CustomTabBar *)self.tabBarController;
    [tabBar hiddenTheTabBarView];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    //    NSLog(@"主页 select >>>%d",indexPath.row);
}

// 蓝牙数据更新回调
- (void)updateView:(KKBLEAcceptType)type {
    if (!_isUpdateView) {
        return;
    }
    NSInteger nowcount = [NSDate compareDate:[NSDate date] withAnotherDay:SN_PublicClass.selectDate];
    if (nowcount == 0) {
        if (!KK_BLESend.isSend) {
        }
        if (type == KKBLEAcceptTypeRealtimeSport || type == KKBLEAcceptTypeDataSport) {
            [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(delayUpdatCenter) object:nil];
            [self performSelector:@selector(delayUpdatCenter) withObject:nil afterDelay:0.5];
        }
        if (type == KKBLEAcceptTypeDataSport || type == KKBLEAcceptTypeDataSleep || type == KKBLEAcceptTypeDataHeart || type == KKBLEAcceptTypeDataOxygen || type == KKBLEAcceptTypeDataPressure) {
            [self updateTableView];
        }
    }
}

- (void)delayUpdatCenter {
    SportModel *centerModel = [SportModel getSportModelFromDBWith:SN_PublicClass.selectDate];
    
    _centerView.model = centerModel;
}

- (void)BecomeActive {
    _isUpdateView = YES;
    [self updateAlldata];
    [self updateTableView];
}

- (void)Becomeback {
    _isUpdateView = NO;
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter]removeObserver:self name:UIApplicationDidBecomeActiveNotification object:nil];
    [[NSNotificationCenter defaultCenter]removeObserver:self name:UIApplicationDidEnterBackgroundNotification object:nil];
}

@end

